package mastermind.gui.actions;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;

import mastermind.game.gameLoop;
import mastermind.gui.Frame;
import mastermind.socket.socketConnect;

public class SubmitAction extends AbstractAction{

	private Frame frame;
	private String finalString;
	
	public SubmitAction(Frame frame)
	{
		this.frame = frame;
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		
		if(frame.getGameStarted() == false)
		{
			String msg = "You must start a game first";
			JOptionPane.showConfirmDialog((Component) null, msg, "Error", JOptionPane.DEFAULT_OPTION);
		}
		else
		{
			socketConnect connect = frame.connect();
			DataInputStream dio = connect.getInputStream();
			DataOutputStream dos = connect.getOutputStream();
		
			if(connect != null && dio != null && dos != null)
			{
				try 
				{
					int turnCount = frame.getTurnCount();
					JTable table = frame.getBoardTable();
					String one = (String) table.getValueAt(turnCount, 0);
					String two = (String) table.getValueAt(turnCount, 1); //get values in cells
					String three = (String) table.getValueAt(turnCount, 2);
					String four = (String) table.getValueAt(turnCount, 3);
					
					if(one.equals("???") || two.equals("???") || three.equals("???") || four.equals("???"))
					{
						String msg = "You must select every cell in the row";
						JOptionPane.showConfirmDialog((Component) null, msg, "Error", JOptionPane.DEFAULT_OPTION);
					}
					else
					{			
						finalString = one.substring(0, 1); //create string that server expects from values
						finalString += two.substring(0, 1);
						finalString += three.substring(0, 1);
						finalString += four.substring(0, 1);
						System.out.println("Final String: " + finalString);
						dos.writeUTF(finalString);
					}
				}
				catch (IOException e) 
				{
					e.printStackTrace();
				}
			}
		}
	}

}
